/*** Grid Plugin 1.0 ***/

//If Object.create method doesnt exist
if (typeof Object.create !== 'function')
{
	Object.create = function(obj)
	{
		function F() {};
		F.prototype = obj;
		return new F();		
	}
}

(function($, window, document, undefined){
	$.fn.Grid = function(options){
		
	};
	$.fn.Grid.options = {
		table : undefined,
		highlightRows : true,
		highlightColumns : true,
		highlightResult : true,
		selectedRow : -1,
		selectedColumn : -1
	};
	
	var Grid = {
		
		//
		//Initialize all the properties
		init : function(options)
		{
			var self = this;
			self.options = $.extend({},$.fn.Grid.options, options);			
			
			if(typeof(options) === "string")
			{
				self.options.table = options;
			}
			
			self.labelTitles();
		},
		
		//
		//Label titles on the chart
		labelTitles : function()
		{
			var self = this;
			var ths = $(self.options.table + " tr th");
			var tds = $(self.options.table + " tr td");
			
			ths.each(function(index){
				$this = $(this);												
				var column = $this.index();
				var row = $this.parent()[0].rowIndex;
				
				if(column === 0 && row === 0)
				{
					$this.attr("data-ref","all");
				}
				else if(column === 0 && row > 0)
				{
					$this.attr("data-ref","drop");					
				}
				else if( column !== 0 && row === 0 )
				{
					$this.attr("data-ref","width");					
				}
				$this.attr("data-col",column);
				$this.attr("data-row",row);
			});
			
			tds.each(function(index){
				$this = $(this);
				var column = $this.index();
				var row = $this.parent()[0].rowIndex;
								
				$this.attr("data-col",column);				
				$this.attr("data-row",row);
			});
		},
		
		//
		//Get elements
		elements : function()
		{
			var $self = this;
			var tds = $self.options.table + " tr td";
			var ths = $self.options.table + " tr th";
			
			$(tds)
				.addClass('td')
				.on("click",function(){
					$this = $(this);
				});
				
			$(ths)
				.addClass('th')
				.on("click",function(){
					$this = $(this);					
					var position = $this.attr("data-ref");
					var filter = $($self.options.table + " tr th[data-ref='" + position + "']");					
					
					filter
						.removeClass("active");
						
					$this
						.addClass("active");
					
					$self.options.selectedRow = position == "drop" ? $this.attr("data-row") : $self.options.selectedRow;
					$self.options.selectedColumn = position == "width" ? $this.attr("data-col") : $self.options.selectedColumn;
			})
		},
		
		//
		//Find coordinates
		Find : function(){
			
		}
	};

	Grid.init(".priceChart");
	Grid.elements();		
	
})(jQuery, window, document);


